-- ************************************************************************** --
--  FreePOPs @mail.polimi.it webmail interface
-- 
--  $Id: skeleton.lua,v 1.12 2007/01/14 16:49:37 gareuselesinge Exp $
-- 
--  Released under the GNU/GPL license
--  Written by Dario Brazzi <dario.brazzi@gmail.com>
--             Edoardo Colombo <edo.gcolombo@gmail.com>
-- ************************************************************************** --

PLUGIN_VERSION = "0.0"
PLUGIN_NAME = "Mail.Polimi.IT"
PLUGIN_REQUIRE_VERSION = "0.2.0"
PLUGIN_LICENSE = "GNU/GPL"
PLUGIN_URL = "http://www.freepops.org"
PLUGIN_HOMEPAGE = "http://www.freepops.org/download.php?module=skeleton.lua"
PLUGIN_AUTHORS_NAMES = {"Dario Brazzi", "Edoardo Colombo"}
PLUGIN_AUTHORS_CONTACTS = {"dario (.) brazzi (at) gmail (.) com",
	"edo (.) gcolombo (at) gmail (.) com"}
PLUGIN_DOMAINS = {"@mail.polimi.it"}
PLUGIN_REGEXES = {"@..."}
PLUGIN_PARAMETERS = { 
	{name="codpers", 
	 description={en="---desc-en---",it==[[
	 codice persona per il login
	 Per esempio codice persona 12345678 
	 test@mail.polimi.it?codpers=12345678
	 ]]}},
}
PLUGIN_DESCRIPTIONS = {
	it=[[Questo plugin &egrave per gli utenti di mail.polimi.it]],
	en=[[This plugin allows to access mail.polimi.it]]
}

-- ************************************************************************** --
--  strings
-- ************************************************************************** --

-- these are the webmail-dependent strings
local polimi_string = {
	
	-- The uri where initialize ssl session
	login_site_before = "https://webmail.polimi.it/stud",
	
	-- The string for login post
	post_string = "login=%s&password=%s",
	post_string_after = "&evn_conferma%3Devento=Conferma", --il % crea conflitto con il string.format
	
	-- The uri where you login
	post_site = "https://aunicalogin.polimi.it/aunicalogin/aunicalogin/controller/IdentificazioneUnica.do?jaf_currentWFID=main&EVN_DEFAULT=evento",
	get_matricola = "https://aunicalogin.polimi.it/aunicalogin/aunicalogin/controller/SceltaMatricola.do?jaf_currentWFID=main&EVN_DEFAULT=evento",
	get_redirect = "https://aunicalogin.polimi.it/aunicalogin/aunicalogin/controller/Redirect.do?jaf_currentWFID=main&EVN_DEFAULT=evento"
	
} 

-- ************************************************************************** --
--  State
-- ************************************************************************** --

-- this is the internal state of the plugin. This structure will be serialized 
-- and saved to remember the state.
internal_state = {
	stat_done = false,
	login_done = false,
	session_id = nil,
	domain = nil,
	name = nil,
	password = nil,
	b = nil,
	codpers = nil
}
--------------------------------------------------------------------------------
-- Serialize the internal_state
--
-- serial. serialize is not enough powerful to correcly serialize the 
-- internal state. The field b is the problem. b is an object. This means
-- that it is a table (and no problem for this) that has some field that are
-- pointers to functions. this is the problem. there is no easy way for the 
-- serial module to know how to serialize this. so we call b:serialize 
-- method by hand hacking a bit on names
--
function serialize_state()
	internal_state.stat_done = false;
	
	return serial.serialize("internal_state",internal_state) ..
		internal_state.b:serialize("internal_state.b")
end
--------------------------------------------------------------------------------
-- The key used to store session info
--
-- This key must be unique for all webmails, since the session pool is one 
-- for all the webmails
--
function key()
	return (internal_state.username or "")..
		(internal_state.domain or "")..
		(internal_state.password or "")..
		(internal_state.codpers or "")
end
-- ************************************************************************** --
-- 
-- This is the interface to the external world. These are the functions 
-- that will be called by FreePOPs.
--
-- param pstate is the userdata to pass to (set|get)_popstate_* functions
-- param username is the mail account name
-- param password is the account password
-- param msg is the message number to operate on (may be decreased dy 1)
-- param pdata is an opaque data for popserver_callback(buffer,pdata) 
-- 
-- return POPSERVER_ERR_*
-- 
-- ************************************************************************** --

-- Is called to initialize the module
function init(pstate)
	freepops.export(pop3server)
	
	log.dbg("FreePOPs plugin '"..
		PLUGIN_NAME.."' version '"..PLUGIN_VERSION.."' started!\n")

	-- the serialization module
	require("serial")
	--	return POPSERVER_ERR_UNKNOWN 
	--end 

	-- the browser module
	require("browser")
	--	return POPSERVER_ERR_UNKNOWN 
	--end
	
	-- checks on globals
	freepops.set_sanity_checks()
		
	return POPSERVER_ERR_OK
end
-- -------------------------------------------------------------------------- --
-- Login to the polimi website
--
function polimi_login()
	-- Create Browser
	--
	internal_state.b = browser.new()
	local b = internal_state.b

	-- Enable SSL
	--
	b:ssl_init_stuff()
	
	-- Let the browser know to follow refresh headers (non so se serve?)
	--
	--b:setFollowRefreshHeader(true)


	-- Retrieve the login page.
	--
	local url = polimi_string.login_site_before
	local body, err = b:get_uri(url)

	-- No connection
	--
	if body == nil then
		log.error_print("Login Failed: Unable to make connection")
		return POPSERVER_ERR_NETWORK
	end
	
	-- controllo presenza cookie di sessione ssl tipo:
	-- "SSL_JSESSIONID=abc75K6gZM-PK5aqs1l_s; path=/; domain=aunicalogin.polimi.it; Secure"
	local sessionssl = (b:get_cookie("SSL_JSESSIONID") or {}).value or "error"
	log.dbg("\nSSL_JSESSIONID:'"..sessionssl.."'\n")
	
	-- create data to send in post login
	local post_data=string.format(polimi_string.post_string,internal_state.codpers,internal_state.password)..
	                polimi_string.post_string_after

	-- post session codice persona e password (OK restituisce messaggio corretto)
	--
	url=polimi_string.post_site
	body, err = b:post_uri(url,post_data)
	
	local str = string.find(body, "ErrorMessage")  --string.match(body,"ErrorMessage") --don't find error
	if str ~= nil then
		log.error_print("Login Failed: username or password wrong")
		return POPSERVER_ERR_AUTH
	end	
	
	url = b:whathaveweread()
	log.dbg("\nBEFORE GET MATRICOLA - whathaveweread()=" .. url)
	
	b:verbose_mode()
	url = polimi_string.get_matricola
	
	-- get matricola (fallisce: 500 Internal Server Error
	--                probabilmente bisogna usare un tipo di browser, magari come ie o firefox vedi altri plugin)
	local head = nil
	head, body, err = b:get_head_and_body(url)
	
	url = b:whathaveweread()
	log.dbg("\nAFTER GET MATRICOLA - b:whathaveweread()=" .. url)

	--url = polimi_string.get_redirect
	--body, err = b:get_uri(url)
	
	--local sso_login = ((b:get_cookie("SSO_LOGIN")) or {}).value or "non trovato"
	--local tickngt = ((b:get_cookie("tickngt")) or {}).value or "non trovato"
	
	--log.dbg("\nSSO_LOGIN:'"..sso_login.."'\n")
	--print("\nSSO_LOGIN:'"..sso_login.."'\n")
	--log.dbg("\ntickngt:'"..tickngt.."'\n")
	--print("\ntickngt:'"..tickngt.."'\n")
	
	return POPSERVER_ERR_AUTH
end
-- -------------------------------------------------------------------------- --
-- Must save the mailbox name
function user(pstate,username)

	-- extract and check domain
	local domain = freepops.get_domain(username)
	local name = freepops.get_name(username)

	-- default is @mail.polimi.it 
	if not domain then
		domain = "mail.polimi.it"
	end

	-- save domain and name
	internal_state.domain = domain
	internal_state.name = name
	-- set person code
	local person_code = (freepops.MODULE_ARGS or {}).codpers or "error"
	--local f64 = base64.encode(f)
	--local f64u = base64.encode(string.upper(f))
	internal_state.codpers = person_code 
	--internal_state.folder_uppercase = f64u

	return POPSERVER_ERR_OK

end
-- -------------------------------------------------------------------------- --
-- Must login
function pass(pstate,password)
	-- save the password
	internal_state.password = password

	-- eventually load session
	local s = session.load_lock(key())
	-- TODO

	-- check if loaded properly
	if s ~= nil then
		-- TODO		
		return POPSERVER_ERR_OK
	else
		-- call the login procedure
		return polimi_login()
	end

end
-- -------------------------------------------------------------------------- --
-- Must quit without updating
function quit(pstate)
	-- for future implementation of session lock&loading
	-- session.unlock(key())
	return POPSERVER_ERR_OK
end
-- -------------------------------------------------------------------------- --
-- Update the mailbox status and quit
function quit_update(pstate)
end
-- -------------------------------------------------------------------------- --
-- Fill the number of messages and their size
function stat(pstate)
end
-- -------------------------------------------------------------------------- --
-- Fill msg uidl field
function uidl(pstate,msg)
end
-- -------------------------------------------------------------------------- --
-- Fill all messages uidl field
function uidl_all(pstate)
end
-- -------------------------------------------------------------------------- --
-- Fill msg size
function list(pstate,msg)
end
-- -------------------------------------------------------------------------- --
-- Fill all messages size
function list_all(pstate)
end
-- -------------------------------------------------------------------------- --
-- Unflag each message merked for deletion
function rset(pstate)
end
-- -------------------------------------------------------------------------- --
-- Mark msg for deletion
function dele(pstate,msg)
end
-- -------------------------------------------------------------------------- --
-- Do nothing
function noop(pstate)
end
-- -------------------------------------------------------------------------- --
-- Get first lines message msg lines, must call 
-- popserver_callback to send the data
function top(pstate,msg,lines,pdata)
end
-- -------------------------------------------------------------------------- --
-- Get message msg, must call 
-- popserver_callback to send the data
function retr(pstate,msg,pdata)
end

-- EOF
-- ************************************************************************** --
